<template>
    <el-dialog title="请上传excel" :visible.sync="isOpen" width="50vw" append-to-body>
        <div class="upload-box">
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="headers" :action="url"
                :disabled="isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                    @click="importTemplate">下载模板</el-link> -->
                </div>
            </el-upload>
            <div ref="chartRef" style="height: 800px; width: 100%;"></div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submit">查 询</el-button>
            <el-button type="danger" @click="reset">清 空</el-button>
            <el-button @click="close">取 消</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import * as echarts from 'echarts';
export default {
    name: 'uploadDialog',
    data() {
        return {
            upload: null,
            chartRef: null,
            myChart: null,
            isOpen: false,
            isUploading: false,
            headers: { Authorization: "Bearer " + getToken() },
            url: process.env.VUE_APP_BASE_API + "/member/sourceInfo/upload",
            chartData: []
        }
    },
    methods: {
        show() {
            this.isOpen = true
        },
        close() {
            this.isOpen = false
        },
        submit() {
            this.$refs.upload.submit();
        },
        handleFileUploadProgress() {
            this.isUploading = true;
        },
        handleFileSuccess(e) {
            console.log(e);
            if (e.rows.length > 0) {
                this.chartData = e.rows
                this.renderChart(e.rows)
            }
        },
        importTemplate() {
            this.download('system/user/importTemplate', {
            }, `user_template_${new Date().getTime()}.xlsx`)
        },
        reset() {
            this.isUploading = false
            this.$refs.upload.clearFiles()
            this.chartData = []
            this.renderChart([])
        },
        renderChart(data) {
            const newData = data.reduce((pre, item) => {
                pre.x.push(item.channelName);
                pre.y.push({
                    name: item.channelName,
                    value: item.countChannel
                });
                return pre
            }, {
                x: [],
                y: []
            })
            // 按值降序排序
            const sortedData = [...newData.y].sort((a, b) => a.value - b.value);
            // 提取排序后的 x 轴标签和值
            const sortedX = sortedData.map(item => item.name);
            const sortedY = sortedData.map(item => item.value);
            this.myChart = echarts.init(this.$refs.chartRef); // 初始化ECharts实例
            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: '{a} <br/>{b} : {c} ',
                    axisPointer: {
                        type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
                    }
                },
                grid: {
                    top: 10,
                    bottom: 30,
                    left: Math.max(...sortedX.map(label => label.length)) * 12 + 50,
                    right: 80
                },
                xAxis: {
                    type: 'value'
                },
                yAxis: {
                    type: 'category',
                    data: sortedX,
                    axisLabel: {
                        show: true, // 确保显示所有标签
                        interval: 0, // 强制显示所有标签（0表示不间隔）
                        inside: false, // 标签显示在外部
                        rotate: 0, // 标签旋转角度（如果需要可以设置旋转）
                        margin: 10, // 标签与轴线之间的距离
                        textStyle: {
                            fontSize: 12 // 调整字体大小
                        }
                    }
                },
                dataZoom: [{
                    type: 'slider', // 滚动条型 dataZoom
                    yAxisIndex: 0,  // 控制y轴
                    start: sortedY.length,      // 默认起始位置
                    end: sortedY.length - 35,        // 默认显示30个条目（可滚动查看更多）
                    height: 400,     // 滚动条高度
                    bottom: 30      // 距离底部位置
                }],
                series: [
                    {
                        name: '渠道号',
                        type: 'bar',
                        stack: 'total',
                        seriesLayoutBy: 'column',
                        barWidth: 20,
                        data: sortedY,
                        label: {
                            show: true,
                            precision: 1,
                            position: 'right',
                            valueAnimation: true,
                            fontFamily: 'monospace'
                        }
                    },
                ]
            };
            // const option = {
            //     title: {
            //         text: '手机号分布归属',
            //         left: 'left'
            //     },
            //     tooltip: {
            //         trigger: 'item',
            //         formatter: '{a} <br/>{b} : {c} ({d}%)'
            //     },
            //     legend: {
            //         type: 'scroll',
            //         orient: 'vertical',
            //         right: 10,
            //         top: 20,
            //         bottom: 20,
            //         data: newData.x
            //     },
            //     series: [
            //         {
            //             name: '渠道号',
            //             type: 'pie',
            //             radius: '70%',
            //             center: ['40%', '50%'],
            //             data: newData.y,
            //             emphasis: {
            //                 itemStyle: {
            //                     shadowBlur: 10,
            //                     shadowOffsetX: 0,
            //                     shadowColor: 'rgba(0, 0, 0, 0.5)'
            //                 }
            //             },

            //         }
            //     ]
            // };
            this.myChart.setOption(option);
        },
    }
}

</script>

<style lang="scss" scoped>
.upload-box {
    display: flex;

}
</style>
